import { verifyUrl } from '@/utils/verify';
import { restRootRoutes } from './layout/rest/rest';
import type { RouteRecordRaw } from 'vue-router';
import { getAppMainList } from '@/router/layout/app-main/app-main.ts';
const whiteList = getWhiteList();

/** 是否有路由权限 */
export function haveRouterPermission(path: string): boolean {
  const userStore = useUserStore();

  return userStore.userInfo?.admin || (!whiteList.includes(path) && userStore.roleMenu.includes(path));
}

/** 给路路径加上级路由的路径 */
export function prefixPathRoutes(routes: RouteRecordRaw[], baseUrl = ''): RouteRecordRaw[] {
  const newRoutes = routes.map((route) => {
    const path = !verifyUrl(route.path) ? mergePath(baseUrl, route.path) : route.path;
    route.path = path || '';
    if (route.children && Array.isArray(route.children) && route.children.length > 0) {
      route.children = prefixPathRoutes(route.children, route.path);
      // if (!route.redirect) {
      //   // 因为没有中间页面所以当有children 时要强制重定向
      //   route.redirect = route.children[0]!.redirect || route.children[0]!.path;
      // }
    }
    return route;
  });

  return newRoutes;
}

/**
 * 递归扩展多级路由为一级路由
 */
export function fatteningRoutes(routes: RouteRecordRaw[]): RouteRecordRaw[] {
  return routes.flatMap((route: RouteRecordRaw) => {
    if (route.children) {
      const newRoute = { ...route };
      delete newRoute.children;
      route.children.unshift(newRoute);
      return fatteningRoutes(route.children);
    } else {
      return route;
    }
  });
}

/**
 * 展开路由 多级路由展开成最多二级路由
 */
export function unfoldRoutes(routes: RouteRecordRaw[]): readonly RouteRecordRaw[] {
  const newRoutes = routes.map((route: RouteRecordRaw) => {
    if (route.children) {
      route.children = fatteningRoutes(route.children);
    }
    return route;
  });
  return newRoutes;
}

/**
 * 合并路径 (路径2为斜杠开头就直接返回路径2,否则就返回组合路径)
 *
 */
function mergePath(u1: string, u2: string): string {
  if (u2) {
    // 路径2为斜杠开头就直接返回路径2,否则就返回组合路径
    const url = u2.startsWith('/') ? u2 : u1 + (u1 === '/' ? '' : '/') + u2;
    // 如果有双斜杠就替换为一个斜杠
    return url.replace(/\/\//g, '/');
  } else {
    // 路径2不存在就直接返回路径1
    return u1;
  }
}

/**
 * 获取白名单
 */
export function getWhiteList(): string[] {
  const list = unfoldRoutes(restRootRoutes());
  const _whiteList: string[] = list.map((item) => item.path).filter((item) => !item.startsWith('/:pathMatch'));
  return _whiteList;
}

/** 根据权限返回路由 */
export function returnRouteBasedOnPermissions() {
  const userStore = useUserStore();

  const filterRoutingPermissions: (list: RouteRecordRaw[]) => RouteRecordRaw[] = (list: RouteRecordRaw[]) => {
    if (userStore.roleMenu.length === 1 && userStore.roleMenu[0] === '*') {
      return list;
    }
    return list.filter((node) => {
      if (userStore.roleMenu.includes(node.path)) {
        if (node.children && node.children.length > 0) {
          node.children = filterRoutingPermissions(node.children);
        }
        return !(node.children && node.children.length === 0);
      }
      return false;
    });
  };

  return filterRoutingPermissions(prefixPathRoutes(getAppMainList()));
}
